﻿using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Common;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.ViewModels;
using System.Windows;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class UserEditPage : Window, INavigableView<UserEditViewModel>
    {
        public UserEditViewModel ViewModel { get; }

        public UserEditPage(UserEditViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
        }

        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            ControlHelper.SetDirtyWindow(this);
        }

        [RelayCommand]
        private void Back()
        {
            Close();
        }

        [RelayCommand]
        private async Task Save()
        {
            UserInfo item = ViewModel.Item;
            if (item == null)
            {
                return;
            }
            if (item.Name.IsNullOrWhiteSpace())
            {
                HandyControl.Controls.Growl.ErrorGlobal("用户账号不能为空");
                Name.Focus();
                return;
            }
            if (item.FullName.IsNullOrWhiteSpace())
            {
                HandyControl.Controls.Growl.ErrorGlobal("姓名不能为空");
                FullName.Focus();
                return;
            }

            if (!ViewModel.IsEdit)
            {
                ViewModel.OnBeforeInsert(withOU: false);
                item.Password = EncryptHelper.ComputeHash(item.Password, item.Name.ToLower());
                item.Creator = App.ViewModel.UserInfo.FullName.ToString();
                item.Creator_ID = App.ViewModel.UserInfo.Id.ToString();
            }
            else
            {
                ViewModel.OnBeforeUpdate(withOU: false);
                item.Editor = App.ViewModel.UserInfo.FullName.ToString();
                item.Editor_ID = App.ViewModel.UserInfo.Id.ToString();
            }
            await ViewModel.Save();
            if (ViewModel.Result.Success)
            {
                Close();
            }
        }

        [RelayCommand]
        private void CompanyValueChanged(string value)
        {
            //Console.WriteLine(value);
            //Console.WriteLine(companyControl.Value);
        }

        [RelayCommand]
        private async Task RefreshTree()
        {
            int id = ViewModel.Item.Id;
            await ViewModel.InitData(id);
        }
    }
}
